python web开发之数据库ORM的 peewee库 动手学习实践笔记

背景

在web开发的时候,一些比较简单的小型系统其实也得ORM框架,显而易见其实开发速度上是提升很多,因为有必要学习一下对应的ORM库。

关于ORM一些说明

关于ORM(Object Relational Mapping,对象关系映射)在python中其实存在几个,主要有的还有SQLAlchemy,不过其实今天咋们的猪脚peewee的内核其实也是基于SQLAlchemy,所以可能应该是更加高效!因为还没做进行具体的测试和数据对比,所以现在还是猜测!
后期我也会继续实践一下关于SQLAlchemy在bottle中的使用!

理论上相关ORM应该具备的能力有:
(1)对象关系映射(数据类型映射,类映射,关系映射)
(2)CURD操作
(3)缓存优化

ORM一些优点:
(1)屏蔽数据库操作细节,开发者不需要通过SQL进行和数据库进行交互,提高开发效率
(2)便捷数据库迁移
(3)缓存技术提高数据库操作效率。

安装

pip install peewee
image.png

示例

因为我这边的环境数据库使用的还是Postgresql,所以示例我就以Postgresql为主:

先通过navicat在本地新建一个测试数据库叫做:test_peewee


image.png

新建一个py文件(LearnPeewee.py):


image.png

#!/usr/bin/evn python
# coding=utf-8
# + + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + +
#        ┏┓   ┏┓+ +
#    ┏┛┻━━━┛┻┓ + +
#    ┃       ┃  
#    ┃   ━   ┃ ++ + + +
#    ████━████ ┃+
#    ┃       ┃ +
#    ┃   ┻   ┃
#    ┃       ┃ + +
#    ┗━┓   ┏━┛
#      ┃   ┃           
#      ┃   ┃ + + + +
#      ┃   ┃    Codes are far away from bugs with the animal protecting   
#      ┃   ┃ +     神兽保佑,代码无bug  
#      ┃   ┃
#      ┃   ┃  +         
#      ┃    ┗━━━┓ + +
#      ┃        ┣┓
#      ┃        ┏┛
#      ┗┓┓┏━┳┓┏┛ + + + +
#       ┃┫┫ ┃┫┫
#       ┗┻┛ ┗┻┛+ + + +
# + + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + +"""
"""
Author = zyx
@Create_Time: 2018/3/21 23:11
@version: v1.0.0
@Contact: 308711822@qq.com
@File: LearnPeewee.py
@文件功能描述:
"""
from peewee import *

# 建立一个PostgresqlDatabase数据库引擎对象,连接到本地的数据库
db = PostgresqlDatabase("test_peewee", host="localhost", port=5432, user="postgres", passwd="123456")
db.connect()

# 定义一个ORM基类,在基类中指定本ORM所使用的数据库
class BaseModel(Model):
    class Meta:
        database = db


# 定义一个Course表(课程表)。继承于BaseModel
class Course(BaseModel):
    id = PrimaryKeyField()  # 课程唯一标识
    title = CharField(null=False)  # 课程名称
    period = IntegerField()  # 学时
    des = CharField()  # 课程描述

    class Meta:
        order_by = {'title', }
        db_table = 'course'  # 定义数据库中表的名称


# 定义一个Teacher表(老师表)。继承于BaseModel
class Teacher(BaseModel):
    id = PrimaryKeyField()  # 唯一标识
    name = CharField(null=False)  # 名称
    gender = BooleanField()  # 性别
    address = CharField()  # address地址
    course_id = ForeignKeyField(Course, to_field='id', related_name='course')

    class Meta:
        order_by = {'name', }
        db_table = 'teacher'  # 定义数据库中表的名称


# 执行建表,只需要执行一次
Course.create_table()
Teacher.create_table()

执行报错:


image.png

原因是:

连接字段参数错误
passwd--->password


# 建立一个PostgresqlDatabase数据库引擎对象,连接到本地的数据库
db = PostgresqlDatabase("test_peewee", host="localhost", port=5432, user="postgres", password="123456")
db.connect()

执行成功后查看一下对应的数据库表的情况:

image.png

代码:

#!/usr/bin/evn python
# coding=utf-8
# + + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + +
#        ┏┓   ┏┓+ +
#    ┏┛┻━━━┛┻┓ + +
#    ┃       ┃  
#    ┃   ━   ┃ ++ + + +
#    ████━████ ┃+
#    ┃       ┃ +
#    ┃   ┻   ┃
#    ┃       ┃ + +
#    ┗━┓   ┏━┛
#      ┃   ┃           
#      ┃   ┃ + + + +
#      ┃   ┃    Codes are far away from bugs with the animal protecting   
#      ┃   ┃ +     神兽保佑,代码无bug  
#      ┃   ┃
#      ┃   ┃  +         
#      ┃    ┗━━━┓ + +
#      ┃        ┣┓
#      ┃        ┏┛
#      ┗┓┓┏━┳┓┏┛ + + + +
#       ┃┫┫ ┃┫┫
#       ┗┻┛ ┗┻┛+ + + +
# + + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + +"""
"""
Author = zyx
@Create_Time: 2018/3/21 23:11
@version: v1.0.0
@Contact: 308711822@qq.com
@File: LearnPeewee.py
@文件功能描述:
"""
from peewee import *
from playhouse.shortcuts import model_to_dict, dict_to_model

# from playhouse.pool import PooledPostgresqlExtDatabase
#
# db = PooledPostgresqlExtDatabase(
#     'my_database',
#     max_connections=8,
#     stale_timeout=300,
#     user='postgres')
#
# class BaseModel(Model):
#     class Meta:
#         database = db

# 建立一个PostgresqlDatabase数据库引擎对象,连接到本地的数据库
db = PostgresqlDatabase("test_peewee", host="localhost", port=5432, user="postgres", password="123456")
db.connect()


# 定义一个ORM基类,在基类中指定本ORM所使用的数据库
class BaseModel(Model):
    class Meta:
        database = db


# 定义一个Course表(课程表)。继承于BaseModel
class Course(BaseModel):
    id = PrimaryKeyField()  # 课程唯一标识
    title = CharField(null=False)  # 课程名称
    period = IntegerField()  # 学时
    des = CharField()  # 课程描述

    class Meta:
        order_by = {'title', }

    table_name = 'course'  # 定义数据库中表的名称


# 定义一个Teacher表(老师表)。继承于BaseModel
class Teacher(BaseModel):
    id = PrimaryKeyField()  # 唯一标识
    name = CharField(null=False)  # 名称
    gender = BooleanField()  # 性别
    address = CharField()  # address地址
    course_id = ForeignKeyField(Course, to_field='id', related_name='course')

    class Meta:
        order_by = {'name', }
        table_name = 'teacher'  # 定义数据库中表的名称


# 执行建表,只需要执行一次
Teacher.drop_table()
Course.drop_table()

# peewee.IntegrityError: 错误:  在 "course" 上的更新或删除操作违反了在 "teacher" 上的外键约束 "teacher_course_id_fkey"
# DETAIL:  键值对(id)=(2)仍然是从表"teacher"引用的.

# 执行建表,只需要执行一次
# Teacher.delete()
Course.create_table()
Teacher.create_table()

# 新增行
obj1 = Course.create(id=1, title='经济学', period=320, des='文理科学生均可选修')
# 把数据对象转成字典
u = model_to_dict(obj1)
print(u)
print('通过create()方法添加数据,它会返回一个模型实例:--->', u)

# 把字典转成数据对象
user_data = {'id': 2, 'username': 'charlie'}
obj1 = dict_to_model(Course, u)
print('把字典转成数据对象:---->', obj1.title)

Course.create(id=2, title='大学英语', period=300, des='大一学生必修课')
Course.create(id=3, title='哲学', period=100, des='必修课')
Course.create(id=104, title='编译原理', period=100, des='计算机系选修')
Teacher.create(name='白阵君', gender=True, address='.1.', course_id=1)
Teacher.create(name='李森', gender=True, address='.2.', course_id=3)
Teacher.create(name='张雯雯', gender=False, address='.3.', course_id=2)
Teacher.create(name='李森222', gender=True, address='.344.', course_id=3)
# 查询一行
record = Course.get(Course.title == '大学英语')
print("课程:%s, 学时:%d" % (record.title, record.period))

# 更新
record.period = 200
record.save()
print('更新')
# 删除
# 查询一行
record = Course.get(Course.title == '大学英语')
print("更新之后---课程:%s, 学时:%d" % (record.title, record.period))

# peewee.IntegrityError: 错误:  在 "course" 上的更新或删除操作违反了在 "teacher" 上的外键约束 "teacher_course_id_fkey"
# DETAIL:  键值对(id)=(2)仍然是从表"teacher"引用的.
# 这里想要删除一门课程,但是这门课程可能有一个老师在占用已解决安排上课了!!想要直接删除课程的话,需要先把占用这门课程的老师给删除

# get()方法只能查询一条,且是唯一的一条数据
teacher_record = Teacher.get(Teacher.course_id == record.id)

print('老师的记录', teacher_record.name)
teacher_record.delete_instance()
print('老师被删除记录')

print('删除课程成功!!!')
print('查询老师!')
# teacher_record = Teacher.get(Teacher.course_id ==record.id)
# for i in teacher_record:
#     print(i.name, i.address)


# 查询所有记录
courses = Course.select()
for i in courses:
    print(i.id, i.title, i.period, i.des)

# 带条件查询,并将结果按period字段倒序排序
courses = Course.select().where(Course.id < 10).order_by(Course.period.desc())
for i in courses:
    print(i.id, i.title, i.period, i.des)

# 统计所有课程的平均学时
total = Course.select(fn.Avg(Course.period).alias('avg_period'))
for i in total:
    print(u"平均学时:", i.avg_period)

# 更新多个记录
Course.update(period=300).where(Course.id > 100).execute()

# 多表连接操作,Peewee会自动根据ForeignKeyField的外键定义进行连接:
Record = Course.select().join(Teacher).where(Teacher.gender == True)
for i in Record:
    print(i.id, i.title, i.period, i.des)

db.close()
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,108评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,699评论 1 296
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,812评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,236评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,583评论 3 288
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,739评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,957评论 2 315
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,704评论 0 204
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,447评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,643评论 2 249
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,133评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,486评论 3 256
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,151评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,108评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,889评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,782评论 2 277
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,681评论 2 272

推荐阅读更多精彩内容

  • 转载,觉得这篇写 SQLAlchemy Core,写得非常不错。不过后续他没写SQLAlchemy ORM... ...
    非梦nj阅读 5,259评论 1 14
  • # Python 资源大全中文版 我想很多程序员应该记得 GitHub 上有一个 Awesome - XXX 系列...
    aimaile阅读 26,301评论 6 428
  • Python 资源大全中文版 我想很多程序员应该记得 GitHub 上有一个 Awesome - XXX 系列的资...
    Clemente阅读 3,241评论 0 54
  • 慧兰瑜伽第五集(p5) 准备:饭后三小时。 这集开始主要讲了这集的内容:主要接受一个呼吸功法和一个静心功法。还有预...
    candycheng阅读 379评论 0 0
  • 作为一只教师队伍里的青椒,课题是职业生涯中的重大任务。 面对即将汹涌而来的潮水,决定提前做一些功课,以避免被...
    筱妍007阅读 997评论 1 2